import React from 'react';
import { Button, Space, Card, Typography, Modal, Form, InputNumber, Input, message, Timeline, Row, Col, Tag, Tooltip, Select } from "antd";
import { ExclamationCircleOutlined } from '@ant-design/icons';
import TheTable from "@/components/TheTable"
import TheUpload from "@/components/TheUpload";
import DistributionServe from './distributionServe';
import ServeInfoModal from './serveInfoModal';
import ServeTimeLineModal from './serveTimeLine'
import TheButton from '@/components/TheButton';
import "../style/style.scss"
import { callCarePreviewPrice, callFeedPreviewPrice, callCareApplyChange, callCareChangePrice, callCalculatePriceWashAndCare, callFeedApplyChange, callFeedChangePrice, callCalculatePrice, callServiceFitServiceSpecs, callPetArchivesList, callCloseSelectByAddressAndType, callCloseServicerApplyOrder, shopSalesReturnLabelList, allocationWhole, forceApplyRefund, clearAllocation } from '@/request/callOrder/orderList.js'
import Calendar from "./calendar"

const { TextArea } = Input;

export default class OrderStep extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      dateList: [],
      chooseDate: [],//选择上门时间
      chooseTimeVisibility: false,//选择上门时间
      refundAllFlag: false,
      chooseDateFlag: false,//选择预约日期
      washAndCareIndex: "",
      refundTotalPrice: "",
      specsId: "",
      newTotalPrice: "",
      oldTotalPrice: "",
      addressId: "",
      payWay: "",
      payChannel: "",
      addressLat: "",
      appointmentDate: "",//选择预约日期
      addressLnt: "",
      skuResult: {},//sku选择的集合
      skuArr: [],
      chooseServiceFlag: false,//选择服务
      chooseFlag: false,//选择宠物
      orderInfo: props.orderInfo, //数据信息
      currentValue: '', //当前进度值
      stepParams: [], //step 文案
      selectedRowsDataSourceAfter: [],
      petType: "",
      serviceType: "",//服务类型FEED("FEED", "喂养"),      CARE("CARE", "洗护");	
      columns: [
        {
          title: '服务',
          dataIndex: "service",
          key: "service",
          render: (_, record) => {
            let serviceType = ''
            let skuInfoValue = [] //规格信息数据值 规格值可能会存在多个 多个情况下、分隔显示
            if (record.skuInfoObj) {
              if (record.skuInfoObj.specValues) {
                skuInfoValue = record.skuInfoObj.specValues.map(v => {
                  return v.specsValue
                }).join('、')
              }
              if (record.skuInfoObj.serviceType) {
                // 服务类型
                switch (record.skuInfoObj.serviceType) {
                  case 'FEED':
                    serviceType = '喂养'
                    break
                  case 'CARE':
                    serviceType = '洗护'
                    break
                  default:
                    serviceType = '-'
                }
              }
            }
            return (
              <div>
                <span>{serviceType ? serviceType : '-'}</span>
                {(serviceType && skuInfoValue) && <span style={{ margin: '0 5px' }}>|</span>}
                <span>{skuInfoValue}</span>
              </div>
            )
          }
        },
        {
          title: '服务时间',
          dataIndex: "orderCode",
          key: "orderCode",
          render: (_, record) => {
            return <Space>
              <span>{record.serviceDate}&nbsp;{record.serviceWeek}&nbsp;{record.serviceStartTime}~{record.serviceFinishTime}</span>
              {record.orderDetailType === 1 && <Tag color="error">变更</Tag>}
            </Space>

          }
        },
        {
          title: '金额（元）',
          dataIndex: "orderAmount",
          key: "orderAmount ",
          render: (text) => {
            return <React.$Price price={text || 0} />
          }
        },
        {
          title: '实付金额（元）',
          dataIndex: "payAmount",
          key: "payAmount",
          render: (text, record) => {
            return (
              <Space>
                <React.$Price price={text || 0} />
                <span style={{ color: 'red' }}>（剩余可退<React.$Price price={record.canRefundPrice || 0} />）</span>
              </Space>

            )
          }
        },
        {
          title: '状态',
          dataIndex: "orderStatus",
          key: "orderStatus",
          render: (text) => {
            let orderStatus = ''
            switch (text) {
              case 'WAIT_PAY':
                orderStatus = '待付款'
                break
              case 'WAIT_ORDER_TAKING':
                orderStatus = '待接单'
                break
              case 'WAIT_SERVICE':
                orderStatus = '待服务'
                break
              case 'IN_PROCESS':
                orderStatus = '服务中'
                break
              case 'FINISH':
                orderStatus = '已完成'
                break
              case 'CLOSE':
                orderStatus = '已关闭'
                break
              default:
                orderStatus = '-'
            }
            return orderStatus
          }
        },
      ],
      columnsUp: [
        {
          title: '服务',
          dataIndex: "service",
          key: "service",
          render: (_, record) => {
            let serviceType = ''
            let skuInfoValue = [] //规格信息数据值 规格值可能会存在多个 多个情况下、分隔显示
            if (record.skuInfoObj) {
              if (record.skuInfoObj.specValues) {
                skuInfoValue = record.skuInfoObj.specValues.map(v => {
                  return v.specsValue
                }).join('、')
              }
              if (record.skuInfoObj.serviceType) {
                // 服务类型
                switch (record.skuInfoObj.serviceType) {
                  case 'FEED':
                    serviceType = '喂养'
                    break
                  case 'CARE':
                    serviceType = '洗护'
                    break
                  default:
                    serviceType = '-'
                }
              }
            }
            return (
              <div>
                <span>{serviceType ? serviceType : '-'}</span>
                {(serviceType && skuInfoValue) && <span style={{ margin: '0 5px' }}>|</span>}
                <span>{skuInfoValue}</span>
              </div>
            )
          }
        },
        {
          title: '服务时间',
          dataIndex: "orderCode",
          key: "orderCode",
          render: (_, record) => {
            return <Space>
              <span>{record.serviceDate}&nbsp;{record.serviceWeek}&nbsp;{record.serviceStartTime}~{record.serviceFinishTime}</span>
              {record.orderDetailType === 1 && <Tag color="error">变更</Tag>}
            </Space>

          }
        },
        {
          title: '金额（元）',
          dataIndex: "orderAmount",
          key: "orderAmount ",
          render: (text) => {
            return <React.$Price price={text || 0} />
          }
        },
        {
          title: '实付金额（元）',
          dataIndex: "payAmount",
          key: "payAmount",
          render: (text, record) => {
            return (
              <Space>
                <React.$Price price={text || 0} />
              </Space>

            )
          }
        },
        {
          title: '状态',
          dataIndex: "orderStatus",
          key: "orderStatus",
          render: (text) => {
            let orderStatus = ''
            switch (text) {
              case 'WAIT_PAY':
                orderStatus = '待付款'
                break
              case 'WAIT_ORDER_TAKING':
                orderStatus = '待接单'
                break
              case 'WAIT_SERVICE':
                orderStatus = '待服务'
                break
              case 'IN_PROCESS':
                orderStatus = '服务中'
                break
              case 'FINISH':
                orderStatus = '已完成'
                break
              case 'CLOSE':
                orderStatus = '已关闭'
                break
              default:
                orderStatus = '-'
            }
            return orderStatus
          }
        },
      ],
      petChooseColumns: [
        {
          title: '宠物昵称',
          dataIndex: "petName",
          key: "petName",
        },
        {
          title: '类型',
          dataIndex: "petSpecies",
          key: "petSpecies",
          render: (text) => {
            let orderStatus = ''
            switch (text) {
              case 0:
                orderStatus = "狗"
                break
              case 1:
                orderStatus = '猫'
                break
              case 2:
                orderStatus = '异宠'
                break
            }
            return orderStatus
          }
        },
        {
          title: '最近修改时间',
          dataIndex: "updateTime",
          key: "updateTime ",
        },
      ],
      nextColumns: [
        {
          title: '服务',
          dataIndex: "service",
          key: "service",
          render: (_, record) => {
            let serviceType = ''
            let skuInfoValue = [] //规格信息数据值 规格值可能会存在多个 多个情况下、分隔显示
            if (record.skuInfoObj) {
              if (record.skuInfoObj.specValues) {
                skuInfoValue = record.skuInfoObj.specValues.map(v => {
                  return v.specsValue
                }).join('、')
              }
              if (record.skuInfoObj.serviceType) {
                // 服务类型
                switch (record.skuInfoObj.serviceType) {
                  case 'FEED':
                    serviceType = '喂养'
                    break
                  case 'CARE':
                    serviceType = '洗护'
                    break
                  default:
                    serviceType = '-'
                }
              }
            }
            return (
              <div>
                <span>{serviceType ? serviceType : '-'}</span>
                {(serviceType && skuInfoValue) && <span style={{ margin: '0 5px' }}>|</span>}
                <span>{skuInfoValue}</span>
              </div>
            )
          }
        },
        {
          title: '服务时间',
          dataIndex: "orderCode",
          key: "orderCode",
          render: (_, record) => {
            return <Space>
              <span>{record.serviceDate}&nbsp;{record.serviceWeek}&nbsp;{record.serviceStartTime}~{record.serviceFinishTime}</span>
              {record.orderDetailType === 1 && <Tag color="error">变更</Tag>}
            </Space>

          }
        },
        {
          title: '金额（元）',
          dataIndex: "orderAmount",
          key: "orderAmount ",
          render: (text) => {
            return <React.$Price price={text || 0} />
          }
        },
        {
          title: '实付金额（元）',
          dataIndex: "payAmount",
          key: "payAmount",
          render: (text, record) => {
            return (
              <Space>
                <React.$Price price={text || 0} />
                <span style={{ color: 'red' }}>（剩余可退<React.$Price price={record.canRefundPrice || 0} />）</span>
              </Space>

            )
          }
        },
        {
          title: '状态',
          dataIndex: "orderStatus",
          key: "orderStatus",
          render: (text) => {
            let orderStatus = ''
            switch (text) {
              case 'WAIT_PAY':
                orderStatus = '待付款'
                break
              case 'WAIT_ORDER_TAKING':
                orderStatus = '待接单'
                break
              case 'WAIT_SERVICE':
                orderStatus = '待服务'
                break
              case 'IN_PROCESS':
                orderStatus = '服务中'
                break
              case 'FINISH':
                orderStatus = '已完成'
                break
              case 'CLOSE':
                orderStatus = '已关闭'
                break
              default:
                orderStatus = '-'
            }
            return orderStatus
          }
        },
        {
          title: '退款金额（元）',
          dataIndex: "refundPriceWeb",
          key: "refundPriceWeb",
          render: (_, record) => {
            let maxPrice = Number(React.$transNum(record.canRefundPrice, 2, -2)) //输入最大值
            return <InputNumber min={0.01} max={maxPrice} precision={2} onChange={(e) => this.getRefundTablePrice(e, record)} />
          }
        },
      ],
      //下一步后的表头  变更的
      columnsUpload: [
        {
          title: '服务',
          dataIndex: "service",
          key: "service",
          render: (_, record) => {
            let serviceType = ''
            let skuInfoValue = [] //规格信息数据值 规格值可能会存在多个 多个情况下、分隔显示
            if (record.skuInfoObj) {
              if (record.skuInfoObj.specValues) {
                skuInfoValue = record.skuInfoObj.specValues.map(v => {
                  return v.specsValue
                }).join('、')
              }
              if (record.skuInfoObj.serviceType) {
                // 服务类型
                switch (record.skuInfoObj.serviceType) {
                  case 'FEED':
                    serviceType = '喂养'
                    break
                  case 'CARE':
                    serviceType = '洗护'
                    break
                  default:
                    serviceType = '-'
                }
              }
            }
            return (
              <div>
                <span>{serviceType ? serviceType : '-'}</span>
                {(serviceType && skuInfoValue) && <span style={{ margin: '0 5px' }}>|</span>}
                <span>{skuInfoValue}</span>
              </div>
            )
          }
        },
        {
          title: '服务时间',
          dataIndex: "orderCode",
          key: "orderCode",
          render: (_, record) => {
            return <Space>
              <span>{record.serviceDate}&nbsp;{record.serviceWeek}&nbsp;{record.serviceStartTime}~{record.serviceFinishTime}</span>
              {record.orderDetailType === 1 && <Tag color="error">变更</Tag>}
            </Space>

          }
        },
        {
          title: '金额（元）',
          dataIndex: "orderAmount",
          key: "orderAmount ",
          render: (text) => {
            return <React.$Price price={text || 0} />
          }
        },
        {
          title: '实付金额（元）',
          dataIndex: "payAmount",
          key: "payAmount",
          render: (text, record) => {
            return (
              <Space>
                <React.$Price price={text || 0} />
              </Space>

            )
          }
        },
        {
          title: '服务者',
          dataIndex: "servicerName",
          key: "servicerName",
          render: (text, record) => {
            return record.servicerName ? <TheButton onClick={() => { this.props.history.push('/call/servicer/servicerList/detail/' + record.servicerId + '/' + 'view') }}>{record.servicerName}</TheButton> : '-'
          }
        },
        {
          title: '状态',
          dataIndex: "orderStatus",
          key: "orderStatus",
          render: (text) => {
            let orderStatus = ''
            switch (text) {
              case 'WAIT_PAY':
                orderStatus = '待付款'
                break
              case 'WAIT_ORDER_TAKING':
                orderStatus = '待接单'
                break
              case 'WAIT_SERVICE':
                orderStatus = '待服务'
                break
              case 'IN_PROCESS':
                orderStatus = '服务中'
                break
              case 'FINISH':
                orderStatus = '已完成'
                break
              case 'CLOSE':
                orderStatus = '已关闭'
                break
              default:
                orderStatus = '-'
            }
            return orderStatus
          }
        },
      ], //下一步后的表头
      updateAfterService: [
        {
          title: '宠物',
          dataIndex: "pet",
          key: "pet",
          render: (_, record) => {
            let txt = ""
            if (record.hasOwnProperty('pet') && record.pet) {
              txt = record.pet.map(item => item.petName).join(',')
            }
            return <Space>
              <TheButton>{txt}</TheButton>
            </Space>
          }
        },
        {
          title: '服务',
          dataIndex: "service",
          key: "service",
          render: (_, record) => {
            let serviceType = ''
            let skuInfoValue = [] //规格信息数据值 规格值可能会存在多个 多个情况下、分隔显示
            if (record.service) {
              // 服务类型
              switch (this.state.serviceType) {
                case 'FEED':
                  serviceType = '喂养'
                  break
                case 'CARE':
                  serviceType = '洗护'
                  break
                default:
                  serviceType = '-'
              }
              if (record.service !== '-' && record.skuInfoObj.specValues) {
                skuInfoValue = Object.values(record.service).map(v => {
                  return v.specsValue
                }).join('、')
                skuInfoValue = { "0": '狗', '1': '猫', '0,1': '有猫有狗' }[record.petType] + '、' + skuInfoValue
              } else {
                skuInfoValue = '-'
              }
            }
            return (
              <div>
                {record.service !== '-' && <span>{serviceType ? serviceType : '-'}</span>
                }
                {(serviceType && skuInfoValue) && record.service !== '-' && <span style={{ margin: '0 5px' }}>|</span>}
                <span>{skuInfoValue}</span>
              </div>
            )
          }
        },
        {
          title: '服务时间',
          dataIndex: "orderCode",
          key: "orderCode",
          render: (_, record) => {
            return <Space>
              <span>{record.serviceDate}&nbsp;{record.serviceWeek}&nbsp;{record.serviceStartTime}~{record.serviceFinishTime}</span>
              {record.orderDetailType === 1 && <Tag color="error">变更</Tag>}
            </Space>

          }
        },
        {
          title: '金额（元）',
          dataIndex: "price",
          key: "price",
          render: (text) => {

            return <React.$Price price={text || 0} />
          }
        },
      ],
      dataSource: [],
      updateData: [],
      selectedRowsDataSource2: [],//存用一下
      selectedRowsDataSource: [],
      selectedRowsUpdate: [],
      selectedRowsPetDataSource: [],//宠物勾选存储数据
      refundCurrentIndex: 1, //退款步骤
      uploadCurrentIndex: 1, //变更步骤
      selectedRowKeys: [],//退款勾选的数据
      selectedPetRowKeys: [],//宠物的数据
      payPriceAll: 0,//退款实付金额总和
      surplusRefundAll: 0, //剩余退款金额总和
      fileListLength: 0,// 退款上传图片数量
      isRefundModal: false,//退款弹窗
      isUpdateModal: false,//变更弹窗
      refundBtnLoading: false,//发起退款按钮loading
      refundPrice: 0,//退款金额 所选择的订单行填写的退款金额
      isDurationModal: false,//分配服务者弹窗
      selectServicerIds: [],//选中分配的服务者id
      selectProvideType: [],//选中分配的服务者类型
      isNegotiateModal: false,//查看服务详情弹窗
      allotFlag: null,//整单分配是否显示
      tableAllOtFlag: null,//订单行分配按钮是否显示
      allocationType: '',//分配方式 整单分配whole 单行分配single
      orderId: undefined,// 整单订单id
      refundFlag: null, //退款按钮显示
      updateFlag: null, //变更按钮显示
      saleRefundList: [],//退款售后原因list
      submitAllotBtnLoading: false,//确认分配按钮loading
      version: null,//订单版本号
      serviceData: [],//服务者列表
      negotiationHistoryContent: null, //订单历史提示消息提示文案
      isServerInfoModal: false, // 查看服务信息图片或者视频的弹窗
      province: "",
      city: "",
      district: "",
      memberId: "",
      mhcServiceId: "",
      updateDataSource: [],//变更后数据
    }
  }
  async componentDidMount() {
    await this.getData()
    // this.setState({
    //   addressLat: this.props.orderInfo.addressLat,
    //   addressLnt: this.props.orderInfo.addressLnt
    // })
    message.config({ maxCount: 1 });
  }
  // 数据处理
  getData = async () => {
    let { allotFlag, refundFlag, negotiationHistoryContent } = this.state
    let { orderInfo } = this.props
    let refundArr = []// 可以进行退款的数组
    let updateArr = []// 可以进行退款的数组
    if (orderInfo) {
      let memberId = orderInfo.memberId
      let orderId = orderInfo.orderId //整单订单id
      let serviceType = orderInfo.serviceType //服务类型FEED("FEED", "喂养"),      CARE("CARE", "洗护");	
      let district = orderInfo.district
      let city = orderInfo.city
      let province = orderInfo.province
      let newOrderStatusArr = [] //过滤出订单行包含订单状态是待接单状态的数据
      let updateFlag = ""
      // 如果订单行有值 继续执行
      if (orderInfo.orderDetailList) {
        //可进行退款的列表数据
        refundArr = orderInfo.orderDetailList.filter(item => {
          if (item.canChange) updateFlag = true
          return item.canRefund
        }).map(v => {
          v.refundPriceWeb = null
          return v
        })
        //可进行变更的列表数据
        updateArr = orderInfo.orderDetailList.filter(item => item.canChange).map(v => { return v })
        //判断是否存在退款数据存在显示退款按钮 不存在不显示
        if (refundArr && refundArr.length > 0) {
          refundFlag = true
        } else {
          refundFlag = false
        }
        // // 判断出当前全部订单行数据是否包含除订单状态 为待接单状态 以及已关闭状态 ， 如果存在其他状态 不会显示整单分配按钮
        // let refundBtnData = orderInfo.orderDetailList.filter(item => item.orderStatus === 'WAIT_SERVICE' || item.orderStatus === 'IN_PROCESS' || item.orderStatus === 'FINISH')
        // if (refundBtnData && refundBtnData.length > 0) {
        //   refundFlag = true
        // } else {
        //   refundFlag = false
        // }
        orderInfo.orderDetailList.map(item => {
          //订单状态 orderStatus 枚举值 WAIT_PAY 待付款 WAIT_ORDER_TAKING 待接单 WAIT_SERVICE 待服务 IN_PROCESS 服务中 FINISH 已完成 CLOSE 已关闭
          if (item.orderStatus !== 'WAIT_ORDER_TAKING' && item.orderStatus !== 'CLOSE') {
            allotFlag = false
          } else {
            // 判断订单行数据没有其他订单状态 只有待接单和已关闭状态  
            if (allotFlag === null) {
              // 查看数组中是否包含待接单状态，如果存在 则显示整单分配按钮，否则不显示
              newOrderStatusArr = orderInfo.orderDetailList.filter(item => item.orderStatus === 'WAIT_ORDER_TAKING')
              if (newOrderStatusArr && newOrderStatusArr.length > 0) {
                allotFlag = true
              } else {
                allotFlag = false
              }
            }
          }
        })
      }
      // 订单下单信息数据处理
      if (orderInfo.negotiationHistory) {
        if (orderInfo.negotiationHistory.content) {
          let obj = JSON.parse(orderInfo.negotiationHistory.content) //把订单信息转成对象 negotiationHistory
          if (obj) negotiationHistoryContent = obj //历史消息记录对象
        }
      }
      this.setState({ memberId, province, city, district, serviceType, orderInfo, allotFlag, refundFlag, orderId, negotiationHistoryContent, dataSource: refundArr, updateData: updateArr, updateFlag })
    }
  }
  // 退款原因下拉列表数据
  getSaleRefundList = async (labelType) => {
    let res = await shopSalesReturnLabelList({ labelType })
    if (res.code === 0) {
      this.setState({ saleRefundList: res.data })
    }
  }
  //打开退款弹窗
  refundModal = () => {
    // let { orderInfo } = this.state
    // let refundArr = []// 可以进行退款的数组
    // if (orderInfo) {
    //   refundArr = orderInfo.orderDetailList.filter(item => item.canRefund).map(v => {
    //     v.refundPriceWeb = null
    //     return v
    //   })
    // }
    this.setState({ isRefundModal: true })
  }
  //打开变更弹窗
  updateModal = () => {
    this.setState({ isUpdateModal: true })
  }

  // 表格勾选 变更
  onSelectChange2 = async (selectedRowKeys, selectedRows) => {
    let payPriceAll = null, surplusRefundAll = null
    selectedRows.map((item) => {
      payPriceAll += Number(item.payAmount)// 计算当前勾选数据的实付金额总和
      // surplusRefundAll += Number(item.canRefundPrice)//计算当前勾选数据的剩余退款金额总和
    })

    this.setState({
      selectedRowKeys: selectedRowKeys,
      payPriceAll,
      // surplusRefundAll,
      selectedRowsDataSource2: selectedRows
    })
  }
  // 表格勾选  退款
  onSelectChange = async (selectedRowKeys, selectedRows) => {
    let payPriceAll = null, surplusRefundAll = null
    selectedRows.map((item) => {
      payPriceAll += Number(item.payAmount)// 计算当前勾选数据的实付金额总和
      // surplusRefundAll += Number(item.canRefundPrice)//计算当前勾选数据的剩余退款金额总和
    })

    this.setState({
      selectedRowKeys: selectedRowKeys,
      payPriceAll,
      // surplusRefundAll,
      selectedRowsDataSource: selectedRows
    })
  }
  // 表格勾选
  onSelectPetChange = async (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedPetRowKeys: selectedRowKeys,
      // surplusRefundAll,
      selectedRowsPetDataSource: selectedRows
    })
  }
  // 上传凭证
  getFileResult(value) {
    if (value.length) {
      let str = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        }
      }).join(',')
      this.RefundFormRef.setFieldsValue({ refundDocuments: str }); //上传图片回显
      this.setState({ fileListLength: value.length }) //记录上传图片个数
    } else {
      this.setState({ fileListLength: 0 })
      this.RefundFormRef.setFieldsValue({ refundDocuments: '' })
    }
  }
  //下一步
  nextRefund = (index) => { // index下一步为2 上一步为1，点击上一步所有表单数据清空 包括上传图片的length也为0
    let { selectedRowKeys, payPriceAll, refundPrice } = this.state
    if (selectedRowKeys.length === 0) {
      message.error('至少需要勾选一条数据！')
      return false
    }
    if (index === 2) {
      this.getSaleRefundList("T")
    }
    this.setState({ refundCurrentIndex: index, fileListLength: 0, refundPrice: 0 })
  }
  //下一步  变更的
  nextUpload = async (index) => { // index下一步为2 上一步为1，点击上一步所有表单数据清空 包括上传图片的length也为0
    let { selectedRowKeys, selectedRowsDataSource2, serviceType } = this.state
    if (selectedRowKeys.length === 0) {
      message.error('至少需要勾选一条数据！')
      return false
    }
    if (index === 2) {
      let res = await callCloseServicerApplyOrder({ orderId: this.state.orderId, orderDetailIdList: selectedRowsDataSource2.map(item => { return item.orderDetailId }) })
      if (res.code === 0) {
        this.setState({
          oldTotalPrice: "",
          newTotalPrice: "",
          refundTotalPrice: "",
          addressLat: res.data.addressLat,
          addressLnt: res.data.addressLnt,
          payWay: res.data.payWay,
          payChannel: res.data.payChannel,
          addressId: res.data.addressId,
          selectedRowsUpdate: res.data.orderDetailList
        })
        if (serviceType === 'CARE') {
          let selectedRowsDataSourceAfter = res.data.orderDetailList.map(item => {
            return {
              pet: item.petInfoObj,
              service: '-',
              orderCode: '-',
              isWashAndCare: true,//是否是洗护默认
            }
          })
          this.setState({ selectedRowsDataSourceAfter })
        }
      }
      this.getSaleRefundList("F")
    }
    let updateAfterService = this.state.updateAfterService
    if (this.state.serviceType === 'CARE' && updateAfterService.length !== 5) {
      updateAfterService.push({
        title: '操作',
        dataIndex: "servicerName",
        key: "servicerName",
        render: (text, record, index) => {
          return <TheButton onClick={() => { this.chooseService(record.pet[0].petSpecies, index) }}>选择服务</TheButton>
        }
      },)
    }
    updateAfterService.push()
    this.setState({ uploadCurrentIndex: index, updateAfterService })

  }
  //下一步  选择宠物的
  nextChooseService = () => { // index下一步为2 上一步为1，点击上一步所有表单数据清空 包括上传图片的length也为0
    let { selectedPetRowKeys, selectedRowsPetDataSource } = this.state
    if (selectedPetRowKeys.length === 0) {
      message.error('至少需要勾选一条数据！')
      return false
    }
    let petType = [... new Set(selectedRowsPetDataSource.map(row => row.petSpecies))].sort().join(',')
    this.chooseService(petType)
  }

  //退款时填写退款金额
  getRefundTablePrice = (number, record) => {
    record.refundPriceWeb = number
    let refundPrice = 0
    this.state.selectedRowsDataSource.map((item) => {
      refundPrice += item.refundPriceWeb ?? 0
    })
    this.setState({ refundPrice: refundPrice * 100 })
  }
  // 取消退款
  refundCancel = () => {
    this.setState({ isRefundModal: false, selectedRowKeys: [], refundCurrentIndex: 1, refundPrice: 0, selectedRowsDataSource: [] })
  }
  //取消变更
  updateCancel = () => {
    if (this.state.uploadCurrentIndex === 2) {
      this.setState({ fileListLength: 0 })
      this.RefundFormRef.setFieldsValue({ refundDocuments: '' })
    }

    this.setState({ isUpdateModal: false, selectedRowsDataSourceAfter: [], selectedRowKeys: [], uploadCurrentIndex: 1, refundPrice: 0, selectedRowsUpdate: [] })
  }
  //确认发起退款
  initiateRefund = () => {
    let { selectedRowsDataSource, orderId } = this.state
    this.setState({ refundBtnLoading: true })
    let forceOrderList = []
    if (selectedRowsDataSource && selectedRowsDataSource.length > 0) {
      forceOrderList = selectedRowsDataSource.map(item => {
        return {
          orderDetailId: item.orderDetailId,//订单详情id
          refundPrice: item.refundPriceWeb * 100  // 退款订单金额
        }
      })
    }
    let flag = false
    selectedRowsDataSource.some(item => {
      if (item.refundPriceWeb === undefined || item.refundPriceWeb === null) {
        flag = true
        message.warning('请输入退款金额');
        return true
      }
    })
    this.RefundFormRef.validateFields().catch(err => {
      return flag = true
    }).then(async (value) => {
      if (!flag) {
        let reason = value.reason ? value.reason.label : null
        let params = {
          orderId, //订单id
          forceOrderList, //选择的退款表格数据信息
          ...value, //表单值
          reason,//退款原因
        }
        let res = await forceApplyRefund({ ...params })
        if (res.code === 0) {
          message.success('发起退款成功,请在售后单查看！')
          this.refundCancel() //关闭弹窗并清空所有勾选以及填写的数据
          this.props.getRequest(orderId)
          // window.location.reload() //分配成功后刷新下页面
        }
        this.setState({ refundBtnLoading: false })
      }
    })
  }
  //服务者列表值
  getServerData = (value) => {
    this.setState({ serviceData: value })
  }
  //打开分配服务者弹窗
  distributionModal = (value, allocationType) => {
    //订单状态 orderStatus 枚举值 WAIT_PAY 待付款 WAIT_ORDER_TAKING 待接单 WAIT_SERVICE 待服务 IN_PROCESS 服务中 FINISH 已完成 CLOSE 已关闭
    if (value) {
      value.orderDetailList.map(item => {
        // allocationNewArr： 已分配订单行数组  过滤出订单行中包含 WAIT_SERVICE 待服务 IN_PROCESS 服务中 FINISH 已完成 的数据 
        let allocationNewArr = value.orderDetailList.filter(v => v.orderStatus === 'WAIT_SERVICE' || v.orderStatus === 'IN_PROCESS' || v.orderStatus === 'FINISH')
        if (allocationNewArr && allocationNewArr.length > 0) {
          return message.error('当前订单已有单行服务已分配，无法整单分配！')
        } else {
          // 所有订单行订单 不存在以进行单行分配直接打开服务者弹窗 否则提示弹窗是否继续分配
          this.setState({ isDurationModal: true, allocationType, orderId: value.orderId, version: value.version })
        }
      })
    }
  }
  // 勾选的服务者id集合
  selectServe = (selectServicerIds) => {
    this.setState({ selectServicerIds })
  }
  // 确认整单分配服务者并关闭对应的弹窗
  submitDistribution = async () => {
    let { selectServicerIds, orderId, version } = this.state
    // 没有选择服务者时 点击分配提示
    if (selectServicerIds === undefined || selectServicerIds.length === 0) { return message.warning('请至少选择一位服务者！') }
    this.setState({ submitAllotBtnLoading: true })
    let res = await allocationWhole({ servicerIds: selectServicerIds, userOrderId: orderId, version })
    if (res.code === 0) {
      message.success('分配成功！')
      this.setState({ isDurationModal: false, selectServicerIds: [] }, () => {
        this.props.getRequest(orderId)
      })
      // window.location.reload() //分配成功后刷新下页面
    }
    if (res.code === 20008) {
      Modal.confirm({
        title: '提醒',
        icon: <ExclamationCircleOutlined />,
        content: '当前订单已进行过单行分配，需取消原先的单行分配方可进行的整单分配，是否取消原先的单行分配，继续整单分配',
        okText: '继续',
        cancelText: '取消',
        onOk: async () => {
          let res = await clearAllocation({ userOrderId: orderId, version })
          if (res.code === 0) {
            let res = await allocationWhole({ servicerIds: selectServicerIds, userOrderId: orderId, version })
            if (res.code === 0) {
              message.success('分配成功！')
              this.setState({ isDurationModal: false, selectServicerIds: [] }, () => {
                this.props.getRequest(orderId)
              })
              // window.location.reload() //分配成功后刷新下页面
            }
          }
        }
      })
    }
    this.setState({ submitAllotBtnLoading: false })
  }
  // 订单信息查看按钮的显示
  serveInfoBtn = (value) => {
    if (value) {
      if (value.operateType) {
        // 在服务信息operateType返回  MHC_POSITION_PUNCH或者MHC_COMPLETE_SERVICE的时候 查看 图片或视频信息
        if (value.operateType === 'MHC_POSITION_PUNCH' || value.operateType === 'MHC_POSITION_PUNCH') {
          return <Button Button type='link' onClick={() => { this.setState({ isServerInfoModal: true }) }}>查看</Button>
        }
        // 在服务信息operateType返回  MHC_MEMBER_SUCCESS_CHANGE   MHC_SERVICER_SUCCESS_CHANGE    MHC_REFUND_SUCCESS_ORDER_DETAIL_CLOSE   查看跳转至售后单详情页 
        if (value.operateType === 'MHC_MEMBER_SUCCESS_CHANGE' || value.operateType === 'MHC_SERVICER_SUCCESS_CHANGE' || value.operateType === 'MHC_REFUND_SUCCESS_ORDER_DETAIL_CLOSE') {
          if (value.relationType) {
            // relationType 0 跳转变更 1 跳转退款
            let path = ''//跳转详情地址
            switch (value.relationType) {
              case '1':
                path = '/call/order/afterSaleOrder/refundDetails/' + value.dataId
                break
              case '0':
                path = '/call/order/afterSaleOrder/changeDetails/' + value.dataId
                break
            }
            return (path && path !== '') && <Button Button type='link' onClick={() => { this.props.history.push(path) }}>查看</Button>
          }
        }
      }
    }
  }

  //预约日期上一步
  datePrevious = () => {
    this.setState({ chooseDateFlag: false })
  }
  closeChooseTimeVisibility = () => {
    this.setState({ closeChooseTimeVisibility: false })
  }

  //操作关闭服务信息查看图片视频弹窗
  getModalOpen = (value) => {
    this.setState({ isServerInfoModal: value })
  }
  // 操作关闭服务信息弹窗
  getServeTimeLineModalOpen = (value) => {
    this.setState({ isNegotiateModal: value })
  }
  chooseService = async (petSpecies, index) => {
    const { serviceType, province, city, district } = this.state
    let skuArr = []
    let specsVos = []
    let mhcServiceId = "", addressLat = "", addressLnt = ""
    let res = await callCloseSelectByAddressAndType({ serviceType: serviceType, province, city, district })
    if (res.code === 0) {
      skuArr = res.data.specsDescribes.filter(it => it.petSpecies == petSpecies)
      specsVos = res.data.specsVos
      mhcServiceId = res.data.mhcServiceId
      // addressLat = res.data.addressLat
      // addressLnt = res.data.addressLnt
    }
    this.setState({ petType: petSpecies, washAndCareIndex: index, chooseServiceFlag: true, skuArr, chooseFlag: false, specsVos, mhcServiceId })
  }
  setChooseFlag = async () => {
    const { memberId } = this.state
    let petArr = []
    let res = await callPetArchivesList({
      memberId,
      petSpeciesList: ["0", "1"],//加个petSpeciesList数组  传 0和1， 后台让写死就行
    })
    if (res.code === 0) {
      petArr = res.data
    }
    this.setState({ chooseFlag: true, petArr })
  }
  chooseCancelFlag = (params) => {
    this.setState({
      chooseFlag: false
    })
  }
  setSkuItem = (it, index) => {
    let arr = this.state.skuResult
    arr["sku_" + index] = it
    this.setState({
      skuResult: arr
    })
  }
  //确认选择完服务
  //length：服务的数量
  confirmChooseService = async (length) => {
    //skuResult : 选中的服务
    //selectedRowsDataSource：待变更的数据
    //selectedRowsPetDataSource：选中的宠物
    //mhcServiceId:新服务id
    //washAndCareIndex:变更订单  洗护时选择服务的下标
    let { selectedRowsUpdate } = this.state
    const { chooseDate, serviceType, washAndCareIndex, payChannel, payWay, addressId, selectedRowsDataSource2, orderId, addressLat, addressLnt, mhcServiceId, selectedRowsDataSource, petType, skuResult, specsVos, selectedRowsPetDataSource, selectedRowsDataSourceAfter } = this.state
    if (chooseDate.length == 0) return message.error('请选择预约时间')
    if (Object.values(skuResult).length == 0) return message.error('请选择服务！')
    if (length !== Object.values(skuResult).length) return message.error('待变更的服务次数和变更后的服务次数不一致！')

    chooseDate.sort((a, b) => {
      if (a.currentDate == b.currentDate) {
        return a.startTime.split(':')[0] - b.startTime.split(':')[0]
      } else {
        return (new Date(a.currentDate)) - (new Date(b.currentDate))
      }
    })

    //规格信息匹配  返回对应sku的父级id
    let specsId = await callServiceFitServiceSpecs({ petType, valueIdList: Object.values(skuResult).map(item => item.serviceSpecsValueId), specsVos })
    if (specsId.code === 0) {
      let price = ""
      if (serviceType === 'FEED') {
        //喂养算价
        //后人不要好奇这里为什么这么写  要在数组里捞详情出来  接口说后台用的接口只能用app的接口  不能给我单出一个详情接口
        price = await callCalculatePrice({
          lnt: addressLnt,
          lat: addressLat,
          operateType: 5,
          serviceId: mhcServiceId,
          changeUserOderDetailIds: selectedRowsUpdate.map(item => item.orderDetailId),
          specsId: specsId.data,
          petInfoBos: selectedRowsPetDataSource,
          reservationTimeBos: chooseDate.map(item => { return { date: item.currentDate, startTime: item.startTime, endTime: item.endTime } })
          // reservationTimeBos: selectedRowsUpdate.map(item => { return { date: item.serviceDate, startTime: item.serviceStartTime, endTime: item.serviceFinishTime } }),
        })
        //如果变更服务条数和选择的日期数量不匹配  就返回
        if (price.code != 0) return
        //将变更前的数据修改时间
        selectedRowsUpdate = selectedRowsUpdate.map((params, index) => {
          return {
            ...params,
            serviceDate: chooseDate[index].currentDate,
            serviceStartTime: chooseDate[index].startTime,
            serviceFinishTime: chooseDate[index].endTime,
          }
        })
      } else if (serviceType === 'CARE') {
        //洗护算价
        //后人不要好奇这里为什么这么写  要在数组里捞详情出来  接口说后台用的接口只能用app的接口  不能给我单出一个详情接口
        price = await callCalculatePriceWashAndCare({
          lnt: addressLnt,
          lat: addressLat,
          serviceId: mhcServiceId,
          operateType: 5,
          changeUserOderDetailIds: [selectedRowsUpdate.map(item => item.orderDetailId)[washAndCareIndex]],
          details: [{
            specsId: specsId.data,
            petInfoBo: selectedRowsDataSourceAfter[washAndCareIndex].pet[0]
          }],
          reservationTimeBo: {
            date: chooseDate[0].currentDate,
            startTime: chooseDate[0].startTime,
            endTime: chooseDate[0].endTime
          },
          // reservationTimeBo: selectedRowsUpdate.map(item => { return { date: item.serviceDate, startTime: item.serviceStartTime, endTime: item.serviceFinishTime } })[washAndCareIndex],
        })
        if (price.code != 0) return
        //将变更前的数据修改时间
        selectedRowsUpdate = selectedRowsUpdate.map((params, index) => {
          return {
            ...params,
            serviceDate: chooseDate[0].currentDate,
            serviceStartTime: chooseDate[0].startTime,
            serviceFinishTime: chooseDate[0].endTime,
          }
        })
      }
      // let specsIdValue = specsId.data
      let selectedRowsDataSourceAfters = []
      if (serviceType === 'FEED') {
        //变更后的表格数据
        selectedRowsDataSourceAfters = selectedRowsUpdate.map((item, index) => {
          let req = "";
          //变更后的价格
          if (price.code == 0) {
            req = price.data.datePrices.filter(it => {
              return item.serviceDate === it.reservationTimeBo.date && item.serviceStartTime === it.reservationTimeBo.startTime && item.serviceFinishTime === it.reservationTimeBo.endTime
            })
          }
          return {
            ...item,
            petType,
            pet: selectedRowsPetDataSource,//selectedRowsPetDataSource:选择的宠物
            service: skuResult,
            price: req[0] ? req[0].payAmount : ''
          }
        })

      } else if (serviceType === 'CARE') {
        //变更后的表格数据
        let item = selectedRowsUpdate[washAndCareIndex]
        let req = "";
        if (price.code == 0) {
          req = price.data.datePrices.filter(it => item.serviceDate === it.reservationTimeBo.date && item.serviceStartTime === it.reservationTimeBo.startTime && item.serviceFinishTime === it.reservationTimeBo.endTime)
        }
        selectedRowsDataSourceAfter[washAndCareIndex] = {
          ...item,
          petType,
          specsId: specsId.data,
          pet: selectedRowsDataSourceAfter[washAndCareIndex].pet,//selectedRowsPetDataSource:选择的宠物
          service: skuResult,
          price: req.length > 0 ? req[0].payAmount : 0
        }
        selectedRowsDataSourceAfters = selectedRowsDataSourceAfter
      }
      let newTotalPrice = "", oldTotalPrice = "", refundTotalPrice = "", refundAllFlag = false
      let afterPrice = ""
      if (serviceType === 'FEED') {
        //喂养变更算价
        afterPrice = await callFeedChangePrice({
          orderId,
          orderDetailIdList: selectedRowsDataSource2.map(item => { return item.orderDetailId }),
          priceQuery: {
            serviceId: mhcServiceId,
            specsId: specsId.data,
            addressId,
            payWay,
            payChannel, callFeedChangePrice,
            petInfoBos: selectedRowsPetDataSource,
            details: selectedRowsDataSourceAfters.map(item => {
              return {
                reservationTimeBo: {
                  date: item.serviceDate,
                  startTime: item.serviceStartTime,
                  endTime: item.serviceFinishTime
                },
                payAmount: item.price
              }
            })
          }
        })
        if (afterPrice.code != 0) return
      } else if (serviceType === 'CARE') {
        let item = selectedRowsDataSourceAfter[washAndCareIndex]
        let arr = []
        selectedRowsDataSourceAfter.map(it => {
          if (!it.isWashAndCare) {
            arr.push({
              specsId: it.specsId,
              payAmount: it.price,
              petInfoBo: it.pet[0]
            })
          }
        })
        if (selectedRowsDataSourceAfter.filter(item => !item.isWashAndCare).length == selectedRowsUpdate.length) {
          //洗护变更算价
          afterPrice = await callCareChangePrice({
            orderId,
            orderDetailIdList: selectedRowsDataSource2.map(item => { return item.orderDetailId }),
            orderParam: {
              addressId,
              serviceId: mhcServiceId,
              payChannel,
              payWay,
              callFeedChangePrice,
              reservationTimeBo: {
                date: item.serviceDate,
                startTime: item.serviceStartTime,
                endTime: item.serviceFinishTime
              },
              details: arr
            }
          })
        }
      }
      if (afterPrice.code == 0) {
        refundAllFlag = afterPrice.data.refundAllFlag
        newTotalPrice = refundAllFlag ? React.$transNum(afterPrice.data.newTotalPrice, 2, -2) : null
        refundTotalPrice = refundAllFlag ? null : React.$transNum(afterPrice.data.refundTotalPrice, 2, -2)
        oldTotalPrice = refundAllFlag ? React.$transNum(afterPrice.data.oldTotalPrice, 2, -2) : null
      }
      this.setState({ chooseDateFlag: false, chooseServiceFlag: false, skuResult: [], selectedRowsDataSourceAfter: selectedRowsDataSourceAfters, refundAllFlag, refundTotalPrice, specsId, newTotalPrice, oldTotalPrice, chooseServiceFlag: false, selectedRowsDataSourceAfter: selectedRowsDataSourceAfters, chooseFlag: false })
    }
  }
  //提交变更
  submitUpdate = async () => {
    const { selectedRowsUpdate, serviceType, refundAllFlag, refundTotalPrice, newTotalPrice, oldTotalPrice, selectedRowsDataSourceAfter, specsId, payChannel, payWay, addressId, selectedRowsDataSource2, orderId, mhcServiceId, selectedRowsPetDataSource } = this.state
    if (selectedRowsDataSourceAfter.filter(item => !item.isWashAndCare).length !== selectedRowsUpdate.length) return message.error('请添加变更服务！')
    this.RefundFormRef.validateFields().then(async (value) => {
      let reason = value.reason ? value.reason.label : null
      let params = {
        ...value, //表单值
        reason,//变更原因	
      }
      if (serviceType === 'FEED') {
        let res = await callFeedApplyChange({
          orderId,
          orderDetailIdList: selectedRowsDataSource2.map(item => { return item.orderDetailId }),
          refundTotalPrice: refundTotalPrice ? React.$transNum(refundTotalPrice, 0, 2) : null,
          newTotalPrice: newTotalPrice ? React.$transNum(newTotalPrice, 0, 2) : null,
          oldTotalPrice: oldTotalPrice ? React.$transNum(oldTotalPrice, 0, 2) : null,
          refundAllFlag,
          ...params,
          priceQuery: {
            serviceId: mhcServiceId,
            specsId: specsId.data,
            addressId,
            payWay,
            payChannel, callFeedChangePrice,
            petInfoBos: selectedRowsPetDataSource,
            details: selectedRowsDataSourceAfter.map(item => {
              return {
                reservationTimeBo: {
                  date: item.serviceDate,
                  startTime: item.serviceStartTime,
                  endTime: item.serviceFinishTime
                },
                payAmount: item.price,
              }
            })
          }
        })
        if (res.code == 0) {
          this.setState({ isUpdateModal: false, selectedRowsDataSourceAfter: [] })
          this.props.getRequest(orderId)
        }
      } else if (serviceType === 'CARE') {
        let item = selectedRowsDataSourceAfter[0]
        let res = await callCareApplyChange({
          orderId,
          orderDetailIdList: selectedRowsUpdate.map(item => { return item.orderDetailId }),
          refundTotalPrice: refundTotalPrice ? React.$transNum(refundTotalPrice, 0, 2) : null,
          newTotalPrice: newTotalPrice ? React.$transNum(newTotalPrice, 0, 2) : null,
          oldTotalPrice: oldTotalPrice ? React.$transNum(oldTotalPrice, 0, 2) : null,
          refundAllFlag,
          ...params,
          orderParam: {
            addressId,
            serviceId: mhcServiceId,
            payWay,
            payChannel,
            reservationTimeBo: {
              date: item.serviceDate,
              startTime: item.serviceStartTime,
              endTime: item.serviceFinishTime
            },
            details: selectedRowsDataSourceAfter.map(item => {
              return {
                specsId: item.specsId,
                payAmount: item.price,
                petInfoBo: item.pet[0]
              }
            })
          }
        })
        if (res.code == 0) {
          this.setState({ isUpdateModal: false, selectedRowsDataSourceAfter: [], uploadCurrentIndex: 1 })
          this.props.getRequest(orderId)
        }
      }

    })
  }
  //获取当前日期函数
  getNowFormatDate() {
    let date = new Date(),
      year = date.getFullYear(), //获取完整的年份(4位)
      month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
      strDate = date.getDate() // 获取当前日(1-31)
    if (month < 10) month = `0${month}` // 如果月份是个位数，在前面补0  
    if (strDate < 10) strDate = `0${strDate}` // 如果日是个位数，在前面补0
    return `${year}-${month}-${strDate}`
  }
  onPanelChange = (value) => {
    this.setState({
      appointmentDate: value.format('YYYY-MM-DD')
    })
  };
  nextChooseSkuService = async () => {
    const { selectedRowsUpdate, washAndCareIndex, selectedRowsDataSourceAfter, petType, mhcServiceId, addressLat, addressLnt, selectedRowsPetDataSource, serviceType, skuResult, specsVos } = this.state
    let serviceReq = await callServiceFitServiceSpecs({ petType, valueIdList: Object.values(skuResult).map(item => item.serviceSpecsValueId), specsVos })
    if (serviceReq.code !== 0) return

    switch (serviceType) {
      case "FEED":
        const res = await callFeedPreviewPrice({
          serviceId: mhcServiceId,
          operateType: 5,
          lat: addressLat,
          lnt: addressLnt,
          // changeUserOderDetailIds: selectedRowsUpdate.map(item => item.orderDetailId),
          specsId: serviceReq.data,
          petInfoBos: selectedRowsPetDataSource
        })
        if (res.code == 0) {
          this.setState({
            chooseDateFlag: true,
            dateList: res.data.datePrices ? res.data.datePrices : []
          })
        }

        break;
      case "CARE":
        const req = await callCarePreviewPrice({
          serviceId: mhcServiceId,
          lat: addressLat,
          lnt: addressLnt,
          operateType: 5,
          // changeUserOderDetailIds: [selectedRowsUpdate[washAndCareIndex].orderDetailId],
          details: [{
            specsId: serviceReq.data,
            petInfoBo: selectedRowsDataSourceAfter[washAndCareIndex].pet[0]
          }],
        })
        if (req.code == 0) {
          this.setState({
            chooseDateFlag: true,
            dateList: req.data.datePrices ? req.data.datePrices : []
          })
        }
        break;
    }
  }
  chooseDate = (params) => {
    this.setState({
      chooseDate: params
    })
  }

  render() {
    const { chooseTimeVisibility, dateList, chooseDateFlag, columnsUp, refundAllFlag, refundTotalPrice, newTotalPrice, oldTotalPrice, selectedPetRowKeys, petArr, skuResult, petChooseColumns, skuArr, chooseServiceFlag, chooseFlag, selectedRowsDataSourceAfter, serviceType, updateAfterService, updateFlag, orderInfo, isServerInfoModal, negotiationHistoryContent, allocationType, selectedRowKeys, saleRefundList, submitAllotBtnLoading, refundFlag, orderId, allotFlag, selectedRowsDataSource, selectedRowsUpdate, refundCurrentIndex, uploadCurrentIndex, isDurationModal, stepParams, isNegotiateModal, columns, columnsUpload, nextColumns, dataSource, updateData, payPriceAll, refundPrice, fileListLength, isRefundModal, isUpdateModal } = this.state
    const rowSelection = {
      selectedRowKeys,
      hideSelectAll: true,
      preserveSelectedRowKeys: true,
      onChange: this.onSelectChange,
    }
    const rowSelection2 = {
      selectedRowKeys,
      hideSelectAll: true,
      preserveSelectedRowKeys: true,
      onChange: this.onSelectChange2,
    }

    const rowPetSelection = {
      type: { FEED: 'checkbox', CARE: 'radio' }[serviceType],
      selectedPetRowKeys,
      hideSelectAll: true,
      preserveSelectedRowKeys: true,
      onChange: this.onSelectPetChange,
    }
    return (
      <div>
        <div style={{ margin: '20px 0', display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
          <Space size={30}>
            <span>订单号：{orderInfo.orderId}</span>
            <span>下单时间：{orderInfo.orderCreateTime}</span>
          </Space>
          <Space size={30}>
            {
              allotFlag && <TheButton haspermi={['call:orderListDetails:distributeAll']} type='default' size='small' onClick={() => { this.distributionModal(orderInfo, 'whole') }}>整单分配</TheButton>
            }
            {
              refundFlag && <TheButton haspermi={['call:orderListDetails:refund']} type='default' size='small' onClick={() => { this.refundModal(orderInfo.orderDetailList) }}>退款</TheButton>
            }
            {
              updateFlag && <TheButton type='default' size='small' onClick={() => { this.updateModal(orderInfo.orderDetailList) }}>变更</TheButton>
            }
          </Space>
        </div>
        {
          negotiationHistoryContent && <Card>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Space direction='vertical' size={10} >
                <span style={{ fontSize: 18, marginBottom: 10 }}>{negotiationHistoryContent.operateName ? negotiationHistoryContent.operateName : ''}&nbsp;&nbsp;&nbsp;{negotiationHistoryContent.operateTime ? negotiationHistoryContent.operateTime : ''}</span>
                <Space>
                  {negotiationHistoryContent.content && <span style={{ color: '#aaa' }}>{negotiationHistoryContent.content}</span>}
                  {
                    this.serveInfoBtn(negotiationHistoryContent)
                  }
                </Space>
              </Space>
              <Button size='small' onClick={() => { this.setState({ isNegotiateModal: true }) }}>查看详情</Button>
            </div>
          </Card>
        }
        {/* 退款弹窗 */}
        <Modal
          width={'55%'}
          title="退款"
          open={isRefundModal}
          destroyOnClose
          footer={null}
          onCancel={() => {
            this.refundCancel()
          }}
        >
          <p>请和宠主协商后再发起平台端的退款操作!</p>
          {refundCurrentIndex === 1 &&
            <div>
              <p>请选择需要发起退款的服务（售后处理中、已关闭或者已结算的服务不显示）</p>
              <TheTable dataSource={dataSource} columns={columns} rowSelection={rowSelection} rowKey={record => record.orderDetailId} />
              <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
                <Button onClick={() => { this.refundCancel() }}>取消</Button>
                <Button onClick={() => { this.nextRefund(2) }}> 下一步 </Button>
              </Space>
            </div>
          }
          {refundCurrentIndex === 2 &&
            <div>
              <TheTable dataSource={selectedRowsDataSource} columns={nextColumns} rowKey={record => record.orderId} />
              <Form ref={(ref) => this.RefundFormRef = ref} wrapperCol={{ span: 12 }} >
                <Form.Item label='实付金额' >
                  <span><React.$price price={payPriceAll} /></span>
                </Form.Item>
                <Form.Item label='退款金额' required>
                  <span style={{ color: 'red' }}><React.$price price={refundPrice} /></span>
                </Form.Item>
                <Form.Item label='退款原因' name='reason' rules={[{ required: true, message: '请选择退款原因' }]} >
                  <Select labelInValue options={saleRefundList} fieldNames={{ label: 'labelReason', value: 'salesReturnLabelId' }} />
                </Form.Item>
                <Form.Item label='退款说明' name='refundExplain' rules={[{ required: true, message: '请输入退款说明' }]} >
                  <TextArea autoSize={{ minRows: 4, maxRows: 6 }} maxLength={200} showCount />
                </Form.Item>
                <Form.Item label={
                  <div>
                    <span>上传凭证</span>
                    <span style={{ color: '#aaaaaa' }}>({fileListLength}/9)</span>
                  </div>
                } name="refundDocuments">
                  <TheUpload getFileResult={(value) => this.getFileResult(value)} maxSize={10} len={9} />
                </Form.Item>
                <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Button onClick={() => { this.nextRefund(1) }}>上一步</Button>
                  <Button type="primary" onClick={this.initiateRefund}>发起退款</Button>
                </Space>
              </Form>
            </div>
          }
        </Modal>
        <Modal
          width={'55%'}
          title="变更"
          open={isUpdateModal}
          destroyOnClose
          footer={null}
          onCancel={() => {
            this.updateCancel()
          }}
        >
          {uploadCurrentIndex === 1 &&
            <div>
              <p>请和宠主和服务者，协商沟通后再发起平台端的变更操作!</p>
              <p>请选择需要发起变更的服务（售后处理中、已关闭或者已完成的服务不显示）</p>
              <TheTable dataSource={updateData} columns={columnsUp} rowSelection={rowSelection2} rowKey={record => record.orderDetailId} />
              <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
                <Button onClick={() => { this.updateCancel() }}>取消</Button>
                <Button onClick={() => { this.nextUpload(2) }}> 下一步 </Button>
              </Space>
            </div>
          }
          {uploadCurrentIndex === 2 &&
            <div>
              <p>待变更服务</p>
              <TheTable dataSource={selectedRowsUpdate} columns={columnsUpload} rowKey={record => record.orderId} />
              <p style={{ marginTop: '20px' }}>变更后服务
                {
                  serviceType === 'FEED' && <TheButton onClick={this.setChooseFlag}>选择服务</TheButton>} </p>
              <TheTable key={JSON.stringify(selectedRowsDataSourceAfter)} dataSource={selectedRowsDataSourceAfter} columns={updateAfterService} locale={{ emptyText: '请选择服务' }} rowKey={record => record.orderId} />
              {refundAllFlag ? <>
                {oldTotalPrice && <div className='rightPrice'>退还原订单金额：¥{oldTotalPrice}</div>
                }
                {newTotalPrice && <div className='rightPrice'>收取新订单金额：¥{newTotalPrice}</div>
                }              </> : <>
                {refundTotalPrice && <div className='rightPrice'>退还服务差价: ¥{refundTotalPrice}</div>
                }              </>
              }
              <p style={{ marginTop: '20px' }} />
              <Form ref={(ref) => this.RefundFormRef = ref} wrapperCol={{ span: 12 }} >
                <Form.Item label='变更原因' name='reason' rules={[{ required: true, message: '请选择变更原因' }]} >
                  <Select labelInValue options={saleRefundList} fieldNames={{ label: 'labelReason', value: 'salesReturnLabelId' }} />
                </Form.Item>
                <Form.Item label='变更说明' name='refundExplain' rules={[{ required: true, message: '请输入变更说明' }]} >
                  <TextArea autoSize={{ minRows: 4, maxRows: 6 }} maxLength={200} showCount />
                </Form.Item>
                <Form.Item label={
                  <div>
                    <span>上传凭证</span>
                    <span style={{ color: '#aaaaaa' }}>({fileListLength}/9)</span>
                  </div>
                } name="refundDocuments">
                  <TheUpload getFileResult={(value) => this.getFileResult(value)} maxSize={10} len={9} />
                </Form.Item>
                <Space style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Button onClick={() => { this.updateCancel() }}>取消</Button>
                  <Button type="primary" onClick={() => this.submitUpdate()}>提交</Button>
                </Space>
              </Form>
            </div>
          }
        </Modal>
        <Modal
          width={'40%'}
          title="选择服务"
          open={chooseServiceFlag}
          destroyOnClose
          style={{ marginTop: '100px' }}
          footer={null}
          onCancel={() => {
            this.setState({ chooseServiceFlag: false, skuResult: [] })
          }}
        >
          {
            skuArr.length > 0 && skuArr[0].specsJsonBOList.map((item, index) => {
              return item.specsKeyName === '宠物分类' ? '' : <div>
                <div>{item.specsKeyName}</div>
                <div style={{ margin: '10px 0' }}>
                  {item.values.map(it => {
                    return <span className='skuItem' onClick={() => this.setSkuItem(it, index)} style={{ borderColor: skuResult["sku_" + index] && skuResult["sku_" + index].serviceSpecsValueId === it.serviceSpecsValueId ? 'red' : '', color: skuResult["sku_" + index] && skuResult["sku_" + index].serviceSpecsValueId === it.serviceSpecsValueId ? 'red' : '' }}>{it.specsValue}</span>
                  })}
                </div>
              </div>
            })
          }
          <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
            {serviceType === 'CARE' && <Button onClick={() => { this.setState({ chooseServiceFlag: false }) }}>取消</Button>
            }
            {serviceType === 'FEED' && <Button onClick={() => { this.setState({ chooseServiceFlag: false, selectedPetRowKeys: [], selectedRowsPetDataSource: [] }); this.setChooseFlag() }}>上一步</Button>
            }
            <Button onClick={() => { this.nextChooseSkuService() }}> 下一步 </Button>

            {/* <Button onClick={() => this.confirmChooseService(skuArr[0].specsJsonBOList.length - 1)}> 确定 </Button> */}
          </Space>
        </Modal>
        <Modal
          width={'40%'}
          title="选择预约日期"
          open={chooseDateFlag}
          destroyOnClose
          footer={null}
          onCancel={() => {
            this.setState({ chooseDateFlag: false })
          }}
        >
          <div style={{ height: '550px' }}>
            <Calendar data={dateList} disableDateStr={this.getNowFormatDate()} chooseDate={this.chooseDate} serviceType={serviceType} />
          </div>
          <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
            <Button onClick={() => { this.datePrevious() }}>上一步</Button>
            <Button onClick={() => { this.confirmChooseService(skuArr[0].specsJsonBOList.length - 1) }}>下一步</Button>
          </Space>
        </Modal>

        <Modal
          width={'40%'}
          title="选择宠物"
          open={chooseFlag}
          destroyOnClose
          footer={null}
          onCancel={() => {
            this.setState({ chooseFlag: false })
          }}
        >
          <TheTable dataSource={petArr} columns={petChooseColumns} rowSelection={rowPetSelection} rowKey={record => record.petArchivesId} />
          <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 20 }}>
            <Button onClick={() => { this.chooseCancelFlag() }}>取消</Button>
            <Button onClick={() => { this.nextChooseService() }}> 下一步 </Button>
          </Space>
        </Modal>
        {/* 分配服务者弹窗 */}
        <Modal
          width={'70%'}
          title="分配服务者"
          open={isDurationModal}
          okText='确认分配'
          confirmLoading={submitAllotBtnLoading}
          onOk={this.submitDistribution}
          destroyOnClose
          onCancel={() => { this.setState({ isDurationModal: false, selectServicerIds: [] }) }}>
          <DistributionServe getServerData={this.getServerData} orderId={orderId} getSelectKeys={this.selectServe} allocationType={allocationType}></DistributionServe>
        </Modal>
        {
          //查看服务信息详情
          isNegotiateModal && <ServeTimeLineModal createType={'2'} history={this.props.history} orderId={orderInfo.orderId} isModalOpen={isNegotiateModal} getModalOpen={this.getServeTimeLineModalOpen}></ServeTimeLineModal>
        }
        {
          // 订单状态下的图片视频查看详情弹窗
          isServerInfoModal && <ServeInfoModal isModalOpen={isServerInfoModal} detailsData={negotiationHistoryContent} getModalOpen={this.getModalOpen}></ServeInfoModal>
        }
      </div >
    )
  }
}